package com.boomsecret.redis;

import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.ResourceBundle;

/**
 * Created by wangjinliang on 2018/1/22.
 */
public final class RedisUtils {

    private static long DEFAULT_EXPIRE = 0L;

    private static JedisPool jedisPool = null;

    private RedisUtils() {}

    static {
        ResourceBundle rb = ResourceBundle.getBundle("redis");
        DEFAULT_EXPIRE = Long.valueOf(rb.getString("redis.expire"));

        int maxActive = Integer.parseInt(rb.getString("redis.pool.maxActive"));
        int maxIdle = Integer.parseInt(rb.getString("redis.pool.maxIdle"));
        int maxWait = Integer.parseInt(rb.getString("redis.pool.maxWait"));
        boolean testOnBorrow = Boolean.parseBoolean(rb.getString("redis.pool.testOnBorrow"));
        String ip = rb.getString("redis.ip");
        int port = Integer.parseInt(rb.getString("redis.port"));
        String pwd = rb.getString("redis.password");

        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxActive);
        config.setMaxIdle(maxIdle);
        config.setMaxWaitMillis(maxWait);
        config.setTestOnBorrow(testOnBorrow);

        if (StringUtils.isNotBlank(pwd)) {
            jedisPool = new JedisPool(config, ip, port, 2000, pwd);
        } else {
            jedisPool = new JedisPool(config, ip, port);
        }
    }

    /**
     * 获取连接池
     */
    public static JedisPool getJedisPool() {
        return jedisPool;
    }

    /**
     * 获取Jedis连接
     */
    public static Jedis getJedis() {
        return getJedisPool().getResource();
    }

    /**
     * 回收Jedis连接
     */
    public static void releaseJedis(Jedis jedis) {
        if (jedisPool != null && jedis != null) {
            getJedisPool().returnResource(jedis);
        }
    }

    /**
     * 销毁Jedis连接
     */
    public static void returnBrokenResource(Jedis jedis) {
        if (jedisPool != null && jedis != null) {
            jedisPool.returnBrokenResource(jedis);
        }
    }

    /**
     * 获取默认过期时间
     */
    public static long getDefaultExpire() {
        return DEFAULT_EXPIRE;
    }
}
